<template>
  <!-- 外层容器 -->
  <div class="daai-collapse-item" :class="{ 'is-disabled': disabled }">
    <!-- 标题部分 -->
    <div
      class="daai-collapse-item__header"
      :class="{
        'is-disabled': disabled,
        'is-active': isActive,
      }"
      :id="`item-header-${name}`"
      @click="itemClickHandle"
    >
      <slot name="title">{{ title }}</slot>
      <!-- 折叠图标 -->
      <Daai-Icon icon="angle-right" class="header-angle" />
    </div>
    <!-- 内容部分 -->
    <Transition name="slide" v-on="transitionEvents">
      <div class="daai-collapse-item__wrapper" v-show="isActive">
        <div class="daai-collapse-item__content" :id="`item-content-${title}`">
          <slot></slot>
        </div>
      </div>
    </Transition>
  </div>
</template>

<script setup>
import { inject, computed } from 'vue'
import { collapseItemProps, collapseContextKey } from './props'
defineOptions({
  name: 'DaaiCollapseItem',
})

const props = defineProps(collapseItemProps)

const collapseConrtext = inject(collapseContextKey) // 获取父组件注入的数据

const isActive = computed(() => {
  // 获取父组件的modelValue
  const { activeNames } = collapseConrtext
  // 判断当前组件的name是否在modelValue中
  return activeNames.value.includes(props.name)
})

const itemClickHandle = () => {
  if (props.disabled) return
  collapseConrtext.handleItemClick(props.name)
}

// 在这个对象里面，会指定过渡开始和结束时的不同样式
const transitionEvents = {
  beforeEnter(el) {
    el.style.height = '0px'
    el.style.overflow = 'hidden'
  },
  enter(el) {
    el.style.height = el.scrollHeight + 'px'
  },
  afterEnter(el) {
    el.style.height = ''
    el.style.overflow = ''
  },
  beforeLeave(el) {
    el.style.height = el.scrollHeight + 'px'
    el.style.overflow = 'hidden'
  },
  leave(el) {
    el.style.height = '0px'
  },
  afterLeave(el) {
    el.style.height = ''
    el.style.overflow = ''
  },
}
</script>

<style lang="scss" scoped></style>
